

$(
    function () {
        $('#linklogin').on('click', function () {
            $('.reg-box').hide();
            $('.login-box').show();
        });

        $('#linkreg').on('click', function () {
            $('.reg-box').show();
            $('.login-box').hide();
        })

        // 为layui表单添加自定义验证规则
        layui.form.verify({
            // 密码长度规则
            pwd: [/^[\S]{6,12}$/, '密码必须6-12位，且不能出现空格'],
            //注册密码验证
            repwd: function (value) {
                let pwd = $('.reg-box [name=password]').val().trim();
                if (pwd !== value) {
                    return alert('两次输入的密码不一致')
                }
            }
        });

        //登陆
        $('#loginform').on('submit', function (e) {
            e.preventDefault();
            const data = {
                username: $('#loginform [name=username]').val().trim(),
                password: $('#loginform [name=password]').val().trim(),
            };
            $.ajax({
                method: "POST",
                url: '/api/login',
                data: data,
                success: (res) => {
                    if (res.status !== 0) return layui.layer.msg(res.message);
                    layui.layer.msg('登陆成功', { time: 1000, icon: -1 }, () => {
                        localStorage.setItem('token', res.token);
                        window.location.href = '/index.html';
                    });

                }
            })

        })

        // 注册

        $('#regform').on('submit', function (e) {
            e.preventDefault();
            const data = {
                username: $('#regform input[name=username]').val().trim(),
                password: $('#regform input[name=password]').val().trim(),
            };
            $.ajax({
                method: 'POST',
                url: '/api/reguser',
                data: data,
                success: (res) => {
                    if (res.status !== 0) return layui.layer.msg(res.message);
                    layui.layer.msg(res.message, { icon: -1, time: 1000 }, () => {
                        $('#linklogin').trigger();
                        this.reset();
                    })
                }
            })
        })







    }
)